<!--  -->
<template>
    <div class="app-container">
      <!-- START 卡片视图 START -->
      <el-card style="margin-bottom: 10px;">
        <!-- START 搜索与添加按扭区域 START -->
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="流程名称">
            <el-input
              v-model="queryParams.deploymentName"
              style="width: 200px"
              size="small"
              placeholder="请输入流程名称"
              clearable
              @clear="clearQueryCon"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              size="mini"
              @click="searchProcessInfo"
            >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
          <el-form-item style="margin-left:40px;">
            <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="openAddDialog">新增</el-button>
            <el-button type="danger" plain size="mini" icon="el-icon-minus" @click="batchDeleteWorkFlow">批量删除</el-button>
          </el-form-item>
        </el-form>
        <!--  END 搜索与添加按扭区域 END -->
      </el-card>
      <!-- END 卡片视图 END -->
  
      <!-- START 流程部署分页列表区域 START -->
      <el-card>
        <el-table
          v-loading="listLoading"
          :data="processDeployList"
          fit
          border
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="部署ID" sortable="custom" align="center" width="310">
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部署名称" :show-overflow-tooltip="true" width="260px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部署时间" width="200px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.deploymentTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="400" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button size="mini" icon="el-icon-delete" type="danger" plain round>
                删除
              </el-button>
              <el-button type="success" icon="el-icon-search" size="mini" plain round @click="openProcDeployImageDialog(row)">
                查看流程图
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="totalCount>0" :total="totalCount" :page.sync="queryParams.currPageNo" :limit.sync="queryParams.pageSize" @pagination="findProcessDeployList" />
      </el-card>
      <!-- END 流程部署分页列表区域 END -->
      <!-- START 流程定义分页列表区域 START -->
      <el-card>
        <el-table
            v-loading="listLoading"
            :data="processDefList"
            fit
            border
            highlight-current-row
            style="width: 100%;"
        >
            <el-table-column label="流程定义ID" sortable="custom" align="center" width="370">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="定义名称" :show-overflow-tooltip="true" width="130px" align="center">
            <template slot-scope="{row}">
                <span>{{ row.name }}</span>
            </template>
            </el-table-column>  -->
            <el-table-column label="定义KEY" :show-overflow-tooltip="true" width="120px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.key }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="版本" :show-overflow-tooltip="true" width="50px" align="center">
            <template slot-scope="{row}">
                <span>{{ row.version }}</span>
            </template>
            </el-table-column> -->
            <el-table-column label="部署ID" :show-overflow-tooltip="true" width="290px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.deploymentId }}</span>
                </template>
            </el-table-column>
            <el-table-column label="资源文件名[bpmn]" :show-overflow-tooltip="true" width="230px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.resourceName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="资源文件名[png]" :show-overflow-tooltip="true" width="230px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.diagramResourceName }}</span>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="proDefPagination.totalCount>0" :total="proDefPagination.totalCount" :page.sync="proDefPagination.currPageNo" :limit.sync="proDefPagination.pageSize" @pagination="findProcessDefList" />
    </el-card>
    <!-- END 流程定义分页列表区域 END -->
        <!-- START 添加流程部署信息弹出对话框窗口 START -->
<el-dialog title="添加流程" :visible.sync="dialogFormVisible" :rules="rules" width="480px">
  <el-form ref="dataFormRef" :model="newProcess" label-position="left">
    <el-row>
      <el-col :span="24">
        <el-form-item label-width="90px" prop="deploymentName" label="流程名称">
          <el-input v-model="newProcess.deploymentName" size="medium" placeholder="请输入流程名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!--:on-change="changeFile"-->
        <el-form-item label-width="90px" label="流程图文件">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/workFlow/addWorkFlow"
            :before-upload="beforeUploadZip"
            :on-error="uploadError"
            :on-change="getFile"
            :http-request="httpRequest"
            accept=".zip"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
          >
            <el-button slot="trigger" size="small" type="primary">请选择流程图文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertData()">
        提交
        </el-button>
        <el-button @click="cancelEvent()">
        重置
        </el-button>
    </div>
    </el-dialog>
    <!-- END 添加流程部署信息弹出对话框窗口  END -->
    <!-- START 流程图显示对话框 START-->
    <el-dialog title="查看流程图" :visible.sync="procImagedialogVisible" width="560px">
      <el-image :src="diagramUrl"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="procImagedialogVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
    <!-- END 流程图显示对话框 END-->

    </div>
  </template>
  <script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  // 例如：import 《组件名称》 from '《组件路径》';
  import { getProcDeployList, getProcDefList,addWorkFlow,showDiagram,deleteWorkFlow,batchDeleteWorkFlow } from '@/api/processManage'
  import pagination from '@/components/Pagination'
  export default {
    // import引入的组件需要注入到对象中才能使用
    components: {
      pagination
    },
    data() {
      // 这里存放数据
        return {
            // 流程部署列表
            processDeployList: [],
            // 流程定义列表
            processDefList: [],
            // 查询条件绑定对象
            queryParams: {
              // 流程名称
              deploymentName: '',
              currPageNo: 1,
              pageSize: 5,
              sort: '+id'
            },
            // 总记录数
            totalCount: 0,
            // 正在加载中
            listLoading: false,
            // 流程定义表格下的分页对象
            proDefPagination: {
                // 流程名称
                deploymentName: '',
                totalCount: 0,
                currPageNo: 1,
                pageSize: 5
            },
            // 用于控制新增和编辑对话框的显示与隐藏
            dialogFormVisible: false,
            newProcess: {
                // 上传的zip文件
                uploadFile: undefined,
                // 流程名称
                deploymentName: ''
            },
            // 添加表单验证规则对象
            rules: {
                deploymentName: [{ required: true, message: '流程名称必填', trigger: 'blur' }]
            },
            fd: {},
            // 用于控制对话框的显示与隐藏
            procImagedialogVisible: false,
            // 流程图的URL地址
            diagramUrl: '',
            // 获取多个复选框被选中的内容
            multipleSelection: [],
            // 获取被选中的流程部署ID
            ids: []
        }
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.findProcessDeployList()
        this.findProcessDefList() 
    },
    // 方法集合
    methods: {
        // 获取所有的流程部署列表分页信息
        findProcessDeployList() {
            // 出现正在加载中
            this.listLoading = true
            getProcDeployList(this.queryParams).then((res) => {
                this.listLoading = false
                this.processDeployList = res.data.list
                // 获取总记录数
                this.totalCount = res.data.totalCount
            }).catch((error) => {
                console.log('流程部署列表查询失败', error)
            })
        },
        // 重置查询条件
        // 重置查询条件，重置按扭的点击事件
        resetQuery() {
            // 清空查询条件
            this.queryParams = {
                // 流程名称
                deploymentName: '',
                currPageNo: 1,
                pageSize: 5
            }
            this.proDefPagination = {
                // 流程名称
                deploymentName: '',
                currPageNo: 1,
                pageSize: 5
            }
            // 重置查询条件，查询所有的流程部署和流程定义列表
            this.findProcessDeployList()
            this.findProcessDefList()
        },
        // 获取所有的流程定义分页列表信息
        findProcessDefList() {
            // 出现正在加载中
            this.listLoading = true
            this.proDefPagination.deploymentName = this.queryParams.deploymentName
            getProcDefList(this.proDefPagination).then((res) => {
                this.listLoading = false
                this.processDefList = res.data.list
                // 获取总记录数
                this.proDefPagination.totalCount = res.data.totalCount
            }).catch((error) => {
                console.log('流程部署列表查询失败', error)
                this.$message({
                type: 'error',
                title: '提示',
                message: '流程部署列表查询失败',
                duration: 2000
                })
            })
        },
        //搜索
        searchProcessInfo() {
            this.findProcessDeployList()
            this.findProcessDefList()
        },

        // 搜索文本框中清空搜索条件时触发
        clearQueryCond() {
            this.findProcessDeployList()
            this.findProcessDefList()
        },
        // 新增按扭的点击事件
        openAddDialog() {
            this.dialogFormVisible = true
            // 重置newProcess对象
            this.newProcess = {
                uploadFile: undefined,
                // 流程名称
                deploymentName: ''
            }
            if (this.$refs.upload) {
                // 清空已上传的流程图zip文件列表
                this.$refs.upload.clearFiles()
            }
        },
        uploadError() {
            this.$message.error('流程文件上传失败!')
        },
        // 流程文件(zip文件)上传前对文件的格式进行判断
        beforeUploadZip(file) {
            var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
            // 限制上传格式为zip
            const extension = testmsg === 'zip'
            if (!extension) {
                this.$message({
                    message: '流程文件只能是zip!',
                    type: 'error',
                    duration: 2000
                })
            }
        },
        getFile(file, fileList) {
            const fd = new FormData()// FormData 对象
            this.fd = fd
        },
        httpRequest(param) {
            const fileObj = param.file // 相当于input里取得的files (即得到要上传的zip文件)
            this.fd.append('uploadFile', fileObj)// 文件对象
        },
        // 添加流程部署信息弹出对话框中[提交]按扭的点击事件
        insertData() {
            this.$refs.dataFormRef.validate((valid) => {
                if (valid) {
                  // 提交el-upload组件上传的流程图zip文件
                  this.$refs.upload.submit()
                  this.fd.append('deploymentName', this.newProcess.deploymentName)
                  // 调用processManage.js中的addWorkFlow方法发送请求到后端实现新增流程部署
                  addWorkFlow(this.fd).then((res) => {
                      // false隐藏新增流程部署对话框
                      this.dialogFormVisible = false
                      if (res.code === 200) {
                        // 新增流程部署成功后，再刷新流程部署信息列表与流程定义信息列表
                        this.findProcessDeployList()
                        // 查询所有的流程定义列表
                        this.findProcessDefList()
                        this.$message({
                            title: '提示',
                            message: res.message,
                            type: 'success',
                            duration: 2000
                        })
                      } else {
                        this.$message({
                            title: '提示',
                            message: res.message,
                            type: 'error',
                            duration: 2000
                        })
                      }
                  })
                }
            })
        },
        openProcDeployImageDialog(row){
          this.procImagedialogVisible=true;

          showDiagram(row.id).then((response) => {
              // 流处理如下
              return 'data:image/png;base64,' + btoa(
                new Uint8Array(response)
                  .reduce((data, byte) => data + String.fromCharCode(byte), '')
              )
          }).then((res)=>{
              this.diagramUrl=res;
          }).catch((err)=>{
              console.log(err);
          })
        },
        // 删除按扭的点击事件
        delProceeDeploy(row) {
          this.$confirm('确认要删除当前流程部署和定义信息吗?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteWorkFlow(row.id).then((res) => {
              if (res.code === 200) { 
                this.$message.success(res.message)
                // 删除成功后，获取最新的流程部署、定义列表信息
                this.findProcessDeployList()
                // 查询所有的流程定义列表
                this.findProcessDefList()
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          }).catch(() => {
            this.$message.info('您取消了删除')
          })
        },
        // 当复选框被选中时，将选中的多个复选择框所在行的数据赋值给multipleSelection
        handleSelectionChange(sels) {
          this.multipleSelection = sels
        },
        // 批量删除按扭的点击事件
        batchDeleteWorkFlow() {
          if (this.multipleSelection && this.multipleSelection.length === 0) {
            this.$message.info('请选择要删除的流程部署信息')
            return
          }
          // 获取复选框选中的流程部署ID
          this.multipleSelection.forEach((selection) => {
            this.ids.push(selection.id)
          })
          this.ids = this.ids.toString()
          this.$confirm('确认要批量删除当前这些请假单信息吗?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            batchDeleteWorkFlow(this.ids).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.message)
                // 删除成功后，获取最新的流程部署、定义列表信息
                this.findProcessDeployList()
                // 查询所有的流程定义列表
                this.findProcessDefList()
              } else {
                this.$message.error(res.message)
              }
            }).catch((err) => {
              this.$message.error(err)
            })
          }).catch(() => {
            this.$message.info('您取消了删除')
          })
        },


    } // 如果页面有keep-alive缓存功能，这个函数会触发
  }
  </script>
  
  
  